import readLine from 'readline';

class GuessNumber {
  private target: string = '';
  private count: number = 0;
  private communication: readLine.Interface;
  private startTime: number = Date.now();

  public start() {
    this.welcome();
    this.generateRandomNumber();
    this.initCommunication();
    this.play();
  }

  private welcome() {
    console.log('欢迎来到猜数字游戏！');
    console.log('每次输入4个数字，然后会返回xAyB，x表示数字和位置都正确的个数，y表示数字正确但位置不正确的个数。');
    console.log('例如：2A1B表示有2个数字和位置都正确，1个数字正确但位置不正确。');
  }

  private initCommunication() {
    this.communication = readLine.createInterface({
      input: process.stdin,
      output: process.stdout,
    })
  }

  private play() {
    this.communication.question('请输入4个数字：', (input) => {
      const result = this.judge(input);
      console.log(result);
      if (result === '4A0B') {
        console.log('恭喜你，猜对了！');
        console.log('你一共猜了', this.count, '次');
        console.log('用时', (Date.now() - this.startTime) / 1000, '秒');
        this.judgeReplay();
      } else {
        this.play();
      }
    })
  }

  private judgeReplay() {
    this.communication.question('是否再玩一次？(是输入Y/结束输入N)', (input) => {
      if (input.toUpperCase() === 'Y') {
        this.generateRandomNumber();
        this.play();
      } else {
        console.log('再见');
        this.communication.close();
      }
    })
  }

  private judge(input: string) {
    if (!/^[1-9]{4}$/.test(input)) {
      console.log('请输入4个数字');
      return;
    }
    this.count++;
    let a = 0;
    let b = 0;
    for (let i = 0; i < input.length; i++) {
      if (input[i] === this.target[i]) {
        a++;
      } else if (this.target.includes(input[i])) {
        b++;
      }
    }
    return `${a}A${b}B`;
  }

  private generateRandomNumber() {
    this.startTime = Date.now();
    this.count = 0;
    this.target = '';
    while (this.target.length < 4) {
      const num = Math.ceil(Math.random() * 9).toString();
      if (!this.target.includes(num)) {
        this.target += num;
      }
    }
  }
}

const guessNumber = new GuessNumber();
guessNumber.start();
